package com.ljw.es;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author: lijunwei
 * @Time: 2020/2/4 16:30
 */
public class ElasticsearchClient {
    public static void main(String[] args) throws UnknownHostException {
        //方式1:在elasticsearch.yml中没有配置集群名称,则使用默认的集群名称
        //TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
        //       .addTransportAddress(new TransportAddress(InetAddress.getByName("118.25.43.248"), 9300));

        //方式2:
        Settings settings = Settings.builder().put("cluster.name", "my-es").build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("118.25.43.248"), 9300));

        //方式三
        // client.transport.sniff=true   //嗅探 默认每5s去更新下集群新的节点，加入新节点，去掉坏节点
        //Settings settings = Settings.builder().put("cluster.name", "my-es").put("client.transport.sniff", true).build();
        //TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName("118.25.43.248"), 9300));

        System.out.println("Elasticsearch connect info:" + client.toString());

        //新增一个index
        IndexResponse response = client.prepareIndex("twitter", "tweet")
                .setId("1")
                .setSource("{'counter':'2','tags':'Add one more!''}")
                .execute()
                .actionGet();
        System.out.println("response.version():" + response.getVersion());


        //根据id查询数据    String index, String type, String id
        GetResponse documentFields = client.prepareGet("weixin-2018.12.30", "doc", "zqBq_mcB_MjWmOcWUcrs").execute().actionGet();
        System.out.println(documentFields.toString());


        client.close();
    }
}
